/*
* TaskFileUp.java
* Created on  2014-7-31 下午3:54
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-7-31       gaoxinyu    初始版本
*
*/
package com.genghis.ptas.util;

import com.genghis.ptas.constant.DictConstant;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 类的描述信息
 *
 * @author fengxuanzhen
 * @version 1.0.1
 */
public class TaskFileUp {
    public static String url(HttpServletRequest request, String taskBasePath, String upTaskName) throws ServletException, IOException {
        String prefix = DateUtil.getSystemDate("yyyyMMDDHHSS");
        String path = request.getSession().getServletContext().getRealPath("/" + DictConstant.TASK_FILE_NAME + "/");
        String taskPath = path + "/" + taskBasePath + "/";
        //创建文件，防文件夹不存在
        File file = new File(taskPath);
        file.mkdirs();
        //接受页面流文件
        InputStream input = FileUp.getInputStream((MultipartHttpServletRequest) request, upTaskName);
        FileUp.uploadFile(input, taskPath, prefix + DictConstant.TASK_TXT);
        //返回试题路径
        String imgFile = taskPath + prefix + DictConstant.TASK_TXT;
        return imgFile;
    }

    public static String file(HttpServletRequest request, String upTaskName) {
        try {
            String taskUrl = url(request, "", upTaskName);
            //创建流对象
            FileInputStream fileInputStream = new FileInputStream(taskUrl);
            //读取数据，并将读取到的数据存储到数组中
            byte[] data = new byte[1024]; //数据存储的数组
            int i = 0; //当前下标
            //读取流中的第一个字节数据
            int n = fileInputStream.read();
            //依次读取后续的数据
            while (n != -1) {
                //将有效数据存储到数组中
                data[i++] = (byte) n;
                //读取下一个字节的数据
                n = fileInputStream.read();
            }
            //解析数据
            String s = new String(data, 0, i);
            fileInputStream.close();
            return s; //输出字符串
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
